﻿using Entity.Package;
using Entity.Service;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Text;
using Tools;

namespace BLL.Business
{
    /// <summary>
    /// 对明细帐业务
    /// </summary>
    public class DetailAccount
    {
        public static void CheckDetailAccount(PackRequestDetailAccount detail, CSocket.ClientThread client)
        {
            try
            {
                PackReturnDetailAccount pkDuiZhangReturn = new PackReturnDetailAccount();
                pkDuiZhangReturn.TradeCode = ((int)TradeCode.对明细帐).ToString();
                byte[] sendPackage = null;

                //1.读取源对账明细文件（410212.0009DZMX是开封农信社前缀，可配置出来）
                var fileName = ConfigurationManager.AppSettings["traceFileSource"] + "\\410212.0009DZMX." + detail.DzDate;
                var flag = false;
                var data = FileUtil.ReadTxt(fileName);
                if (data != null)
                {
                    //2.转换成中间对账文件
                    var totalStr = $"{detail.StrokeCount.Trim()}|{detail.PayMoneyHJ.Trim()}";
                    //交易流水
                    var traceList = new List<string>();

                    for (int i = 0; i < data.Rows.Count; i++)
                    {
                        //交易时间
                        var dateStr = data.Rows[i]["PayDate"].ToString();
                        var payDate = $"{dateStr.Substring(0, 4)}-{dateStr.Substring(4, 2)}-{dateStr.Substring(6, 2)}";

                        //增加对账流水
                        traceList.Add($"{data.Rows[i]["GasUserID"]}|{data.Rows[i]["FlowNumber"]}|{data.Rows[i]["PayMoney"]}|{payDate}|NXS");
                    }

                    //解析并转换成中间对账文件
                    flag = FileUtil.WriteTraceFile(new PackTraceFileData
                    {
                        FilePath = ConfigurationManager.AppSettings["traceFileTemp"].ToString(),
                        FileName = "NXS" + detail.DzDate + ".txt",
                        Total = totalStr,
                        TraceRows = traceList
                    }, out string errMsg);
                }
                if (flag)
                {
                    // 给银行发送成功返回包(接收包成功，不做处理，对账服务处理)
                    pkDuiZhangReturn.StrokeCount = detail.StrokeCount.Trim();
                    pkDuiZhangReturn.PayMoneyHJ = detail.PayMoneyHJ.Trim();
                    pkDuiZhangReturn.ResponseCode = ((int)ResponseCode.交易成功).ToString().PadLeft(3, '0');
                    pkDuiZhangReturn.PackHead = new PackHead(detail.packHead.PayWay, detail.packHead.BankWaterNumber, (Encoding.Default.GetBytes(pkDuiZhangReturn.ToString()).Length).ToString());
                    sendPackage = CSocket.PackageHandle.CombinationPackage(pkDuiZhangReturn);
                    if (client.Send(sendPackage))  //发送返回包
                        client.CloseSocket();  //断开链接
                }
                else
                {
                    PackFailReturn pkFailReturn = new PackFailReturn();
                    pkFailReturn.TradeCode = ((int)TradeCode.对明细帐).ToString();
                    pkFailReturn.ResponseCode = ((int)Common.GetNoSuccessCode(ResultType.Error)).ToString().PadLeft(3, '0');
                    pkFailReturn.PackHead = new PackHead(detail.packHead.PayWay, detail.packHead.BankWaterNumber, (Encoding.Default.GetBytes(pkFailReturn.ToString()).Length).ToString());

                    CSocket.PackageHandle.SendFailurPackage(pkFailReturn, client);

                    LogHelper.WriteInfoLog($"转换对账文件失败！【日期{detail.DzDate};交易总笔数{detail.StrokeCount}; 交易总金额{detail.PayMoneyHJ}】");
                }

            }
            catch (Exception ex)
            {
                LogHelper.WriteErrorLog("CheckDetailAccount方法-核对明细帐出现异常，异常信息：" + ex.Message, ex);
                PackFailReturn pkFailReturn = new PackFailReturn();
                pkFailReturn.TradeCode = ((int)TradeCode.对明细帐).ToString();
                pkFailReturn.ResponseCode = ((int)ResponseCode.其他错误).ToString().PadLeft(3, '0');
                pkFailReturn.PackHead = new PackHead(detail.packHead.PayWay, detail.packHead.BankWaterNumber, (Encoding.Default.GetBytes(pkFailReturn.ToString()).Length).ToString());
                CSocket.PackageHandle.SendFailurPackage(pkFailReturn, client);

            }
        }
    }
}
